package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 首先判断各种异常：用户的地址簿是否为空，用户购物车中的商品是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null
        ) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 查询当前用户的购物车数据是否为空
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 然后往订单表中插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());

        // 因为后面要往订单明细表中插入数据，所以需要返回订单表的id
        // <insert id="submit" useGeneratedKeys="true" keyProperty="id">
        orderMapper.submit(orders);
        // 往订单明细表中插入n条数据
        // 遍历购物车，得到每一个商品
        // 批量插入
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCarts) {
            // 得到每一个商品后,把商品信息拷贝到订单明细表中
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            // 设置当前订单明细表关联的订单表id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);
        // 清空用户购物车中的数据
        shoppingCartMapper.cleanShoppingCart(userId);
        // 封装成VO对象，返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        // 通过websocket向管理端推送消息 type、orderId、content
        Map map = new HashMap<>();
        map.put("type",1); // 1表示来单提醒  2表示客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号"+outTradeNo);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 根据id查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO selectByOrdersAndOrderDetail(Long id) {
        // 首先根据id查询订单表中的信息
        Orders orders = orderMapper.getByOrders(id);
        // 其次，根据订单id和订单明细表中的order_id字段相等查询订单明细表，并且返回的是一个list集合
        List<OrderDetail> orderDetail = orderDetailMapper.getByOrderDetail(id);
        // 最后封装成vo对象并返回
        OrderVO orderVO = new OrderVO();

        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetail);

        AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
        orderVO.setAddress(addressBook.getProvinceName() + addressBook.getCityName()
                + addressBook.getDistrictName() + addressBook.getDetail());

        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Transactional
    @Override
    public void cancel(Long id) throws Exception {
        Orders orders = orderMapper.getByOrders(id);
        // 首先要判断该订单是否存在
        if (orders == null) {
            // 如果为空则抛出订单不存在异常
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 如果订单存在，那么首先要判断该订单状态是什么状态
        // 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orders.getStatus() > 2) {
            //如果订单状态处于已接单、派送中、已完成则取消失败，抛出异常，需要用户和商家电话联系
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR + "，请和商家联系");
        } else if (orders.getStatus() == 2) { // 如果订单状态处于待接单用户取消，那么商家需要给用户退款
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    orders.getNumber(), //商户订单号
                    orders.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额
            //修改支付状态为退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 设置订单状态为已取消
        orders.setStatus(Orders.CANCELLED);
        // 设置订单取消时间
        orders.setCancelTime(LocalDateTime.now());
        // 设置订单取消原因
        orders.setCancelReason("用户取消");
        // 数据库中修改订单信息
        orderMapper.update(orders);
    }

    /**
     * 再来一单 实际上只是用户把之前订单数据，重新插入到购物车表中
     *
     * @param id
     */
    @Override
    public void insert(Long id) {
        // 首先根据订单id查询出之前的订单
//        Orders orders = orderMapper.getByOrders(id);
        Long userId = BaseContext.getCurrentId();
        // 查询出订单明细表中的数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderDetail(id);
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCartList.add(shoppingCart);
            shoppingCartMapper.insert(shoppingCart);
        }

    }

    /**
     * 用户历史订单分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 开启分页查询
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 获取用户userId
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        // 设置分页条件查询
        Page<Orders> page = orderMapper.historyOrders(ordersPageQueryDTO);
        List<OrderVO> orderVOList = new ArrayList<>();
        // 如果page不为空，并且所有订单总数量大于零
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                // 遍历查询的每一条订单，根据订单id查询订单明细表中该订单中的订单明细
                List<OrderDetail> orderDetail = orderDetailMapper.getByOrderDetail(orders.getId());
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetail);
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO countByOrdersStatus() {
        // 三种订单状态：待接单、带派送、派送中
        Integer toBeConfirmed = orderMapper.countByOrdersStatus(Orders.PENDING_PAYMENT);
        Integer confirmed = orderMapper.countByOrdersStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countByOrdersStatus(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void acceptOrders(OrdersConfirmDTO ordersConfirmDTO) {
        // 根据id查询，修改订单状态
        Orders orders = orderMapper.getByOrders(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    /**
     * 管理端订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult orderSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage = orderMapper.historyOrders(ordersPageQueryDTO);
        List<OrderVO> orderVOList = new ArrayList<>();
        // 如果page不为空，并且所有订单总数量大于零
        if (ordersPage != null && ordersPage.getTotal() > 0) {
            for (Orders orders : ordersPage) {
                // 遍历查询的每一条订单，根据订单id查询订单明细表中该订单中的订单明细
                List<OrderDetail> orderDetail = orderDetailMapper.getByOrderDetail(orders.getId());
                AddressBook addressBook = addressBookMapper.getById(orders.getAddressBookId());
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetail);
                orderVO.setAddress(addressBook.getProvinceName() + addressBook.getCityName()
                        + addressBook.getDistrictName() + addressBook.getDetail());
                String orderDishes = getOrderDishesStr(orders);
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     * @throws Exception
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        Orders orders = orderMapper.getByOrders(ordersCancelDTO.getId());
        // 判断支付状态是否付款
        Integer status = orders.getPayStatus();
        if (status == 1) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    orders.getNumber(), //商户订单号
                    orders.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额
            //修改支付状态为退款
            orders.setPayStatus(Orders.REFUND);
        }
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orders.setStatus(Orders.CANCELLED);
        orderMapper.update(orders);
    }

    /**
     * 商家拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        // 首先根据id查询该订单是否存在
        Orders orders = orderMapper.getByOrders(ordersRejectionDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }else {
            // 订单不是空，则修改订单状态、给用户退款、设置修改时间
            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    orders.getNumber(), //商户订单号
//                    orders.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额
            //修改支付状态为退款
            orders.setPayStatus(Orders.REFUND);
            orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            // 最后修改订单信息
            orderMapper.update(orders);
        }
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        // 首先根据id查询该订单是否存在
        Orders orders = orderMapper.getByOrders(id);
        if (orders != null) {
            // 订单不是空，则修改订单状态、设置修改时间
            orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
            orders.setDeliveryTime(LocalDateTime.now());
            LocalDateTime time = LocalDateTime.now().plusMinutes(60);
            orders.setEstimatedDeliveryTime(time);
            // 最后修改订单信息
            orderMapper.update(orders);
        }
    }

    /**
     * 完成订单
     * @param id
     */

    @Override
    public void complete(Long id) {
        // 首先根据id查询该订单是否存在
        Orders orders = orderMapper.getByOrders(id);
        if (orders != null) {
            // 订单不是空，则修改订单状态、设置修改时间
            orders.setStatus(Orders.COMPLETED);
            orders.setCheckoutTime(LocalDateTime.now());
            // 最后修改订单信息
            orderMapper.update(orders);
        }
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 首先根据id查询该订单是否存在
        Orders orders = orderMapper.getByOrders(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 通过websocket向管理端推送消息 type、orderId、content
        Map map = new HashMap<>();
        map.put("type",2); // 1表示来单提醒  2表示客户催单
        map.put("orderId",id);
        map.put("content","订单号"+orders.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderDetail(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }
}
